/**************************************************
 * Project Name         [JavaEE_XML]
 * File Name            [WebSpider.java]
 * Creation Date        [08-19-2014]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 **************************************************/
package pkg_02_sax;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

/**
 * 模拟网络爬虫
 * 
 * @author 不落的太阳(Sean Yang)
 * @version 1.0
 * @since JDK 6
 * 
 */
public class WebSpider {

	/**
	 * Web Spider
	 * 
	 * @param url
	 * @throws ParserConfigurationException
	 * @throws SAXException
	 * @throws MalformedURLException
	 * @throws IOException
	 */
	public static void webSpider1(String url)
			throws ParserConfigurationException, SAXException,
			MalformedURLException, IOException {
		DefaultHandler handler = new DefaultHandler() {
			@Override
			public void startElement(String uri, String localName,
					String qName, Attributes attributes) throws SAXException {
				if ("a".equalsIgnoreCase(localName) && attributes != null) {
					for (int i = 0; i < attributes.getLength(); i++) {
						if ("href".equalsIgnoreCase(attributes.getLocalName(i))) {
							System.out.println(attributes.getValue(i));
						}
					}
				}
			}
		};

		SAXParserFactory factory = SAXParserFactory.newInstance();
		factory.setNamespaceAware(true);
		SAXParser parser = factory.newSAXParser();
		parser.parse(new URL(url).openStream(), handler);
	}

	public static void webSpider2(String url) throws MalformedURLException,
			XMLStreamException, IOException {
		XMLInputFactory factory = XMLInputFactory.newFactory();
		XMLStreamReader parser = factory.createXMLStreamReader(new URL(url)
				.openStream());
		while (parser.hasNext()) {
			int event = parser.next();
			if (event == XMLStreamConstants.START_ELEMENT) {
				if ("a".equals(parser.getLocalName())) {
					String href = parser.getAttributeValue(null, "href");
					if (href != null) {
						System.out.println(href);
					}
				}
			}
		}
	}

	public static void main(String[] args) {
		String url = "http://www.w3c.org";
		try {
			webSpider2(url);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
